package crons;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import search.ArticleSearchEngine;
import systems.ConfigSystem;
import systems.Recently;

import models.ArticleModel;
import debugs.ArticleDebug;
import entities.Article;
import entities.ArticleSearch;
import entities.SiteConfig;

@SuppressWarnings("serial")
public class CronPublishArticle extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		SiteConfig siteConfig = ConfigSystem.getConfigs();
		if (siteConfig.getSubmitStatus() == 0) {
		
			ArticleModel articleModel = ArticleModel.getInstance();
			List<Article> articles = articleModel.getArticleUnpublish();
			
			Article article = null;
			for (int i = 0; i < articles.size(); i++) {
				
				if (!articles.get(i).isPublished()) {
					article = articleModel.getArticle(articles.get(i).getId());
					if (article != null && !article.isPublished()) {
						article.setPublished(true);
						articleModel.insert(article);
						
						ArticleSearch articleSearch = ArticleSearch.convert(article);
						ArticleSearchEngine.update(articleSearch);
						
						//Update recently Cache
						if (article.isPublished()) {
							Recently.update(article);
						}
						
						response.getWriter().println("Published article id " + article.getId() + " success.");
					}
				}
			}
		} else {
			response.getWriter().println("Submit config status is " + siteConfig.getSubmitStatus());
		}
	}
}
